﻿using ExcellentProjectPlus.Infraestructura.CrossCutting.Notificaciones;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace ExcellentProjectPlus.Infraestructura.Notificaciones
{
    public class NotificationService : INotificationService
    {
        public static string Username = ConfigurationManager.AppSettings["NotificationUser"];//"notificaciones.uestar@gmail.com";
        public static string Password = ConfigurationManager.AppSettings["UserPassword"];//"Admin2014";
        ////public const string SmtpServer = "outlook.office365.com";
        public static string SmtpServer = ConfigurationManager.AppSettings["SmtpServer"];//"smtp.gmail.com";
        public static int SmtpPort = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]);

        public static void SendMail(string recipient, string subject, string body, string[] attachments)
        {
            System.Net.Mail.SmtpClient smtpClient = new SmtpClient();
            NetworkCredential basicCredential = new NetworkCredential(Username, Password);
            MailMessage message = new MailMessage();
            MailAddress fromAddress = new System.Net.Mail.MailAddress(Username);

            // setup up the host, increase the timeout to 5 minutes
            smtpClient.Host = SmtpServer;
            smtpClient.Port = SmtpPort;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.EnableSsl = true;
            smtpClient.Credentials = basicCredential;
            smtpClient.Timeout = (60 * 10 * 1000);

            message.From = fromAddress;
            message.Subject = subject + " - " + DateTime.Now.Date.ToString().Split(' ')[0];
            message.IsBodyHtml = true;
            message.Body = body.Replace("\r\n", "<br>");
            message.To.Add(recipient);

            //smtpClient.EnableSsl = true; 
            //smtpClient.Port = 587;
            //smtpClient.Port = 465;

            if (attachments != null)
            {
                foreach (string attachment in attachments)
                {
                    message.Attachments.Add(new Attachment(attachment));
                }
            }

            smtpClient.Send(message);
        }

        public void Notify(string from, string @for, string subject, string data)
        {
            SendMail(@for, subject, data, null);
        }
    }
}
